/*

*/


define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojo/_base/array',
      'dijit/MenuItem',
      'dijit/focus'
   ],
   function(declare, lang, array, MenuItem, focusUtil)
   {
      return declare([],
      {
         mLoadingItem: null, 
         clear: function()
         {
            var pMenuItems = this.getChildren();
            this.set('selected', null);
            array.forEach(pMenuItems, lang.hitch(this, function(item)
            {
               this.onItemUnhover(item);
               item.destroyRecursive();
               this.removeChild(item);
            }));
         },
         onOpen: function()
         {
            if(this.mDeferred)
            {
               this.mDeferred.cancel();
               this.mDeferred = null;
               return;
            }

            if(!this.urlFunc && !this.url)
            {
               this.inherited(arguments);
               return;
            }

            this.clear();

            if(this.urlFunc)
            {
               this.mDeferred = this.urlFunc();
            }
            else
            {
               var xhrArgs = {
                  url: this.url,
                  handleAs: 'json'
               };
               this.mDeferred = dojo.xhrGet(xhrArgs);
            }
            if(!this.mDeferred)
            {
               this.onCancel();
               return;
            }

            this.mDeferred.then(lang.hitch(this, function(data)
            {
               this.mDeferred = null;
               this.createMenu(data);
               if(this.mLoadingItem)
               {
                  var pMenuItems = this.getChildren();
                  if(pMenuItems.length > 1)
                  {
                     var firstNonLoadingItem = pMenuItems[1];
                     this.onItemHover(firstNonLoadingItem);
                     focusUtil.focus(firstNonLoadingItem.domNode);
                  }
                  this.onItemUnhover(this.mLoadingItem);
                  this.mLoadingItem.destroy();
                  this.removeChild(this.mLoadingItem);
                  this.mLoadingItem = null;
               }
            }));

            this.mLoadingItem = new MenuItem({
               label:"Loading...",
               iconClass:"dijitIcon icons-fugue-icons-16x16-clock",
               custId:"loading",
               disabled: true
            });
            this.addChild(this.mLoadingItem);
            this.inherited(arguments);
         },
         onClose: function()
         {
            this.inherited(arguments);
            this.clear();
         }
      });
   }
);
